package com.db.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.druid.util.StringUtils;
import com.db.common.annotation.RequiredLog;
import com.db.common.exception.ServiceException;
import com.db.common.vo.PageObject;
import com.db.common.vo.SysUserDeptVo;
import com.db.dao.SysUserDao;
import com.db.dao.SysUserRoleDao;
import com.db.pojo.SysUser;
import com.db.service.SysUserService;

import lombok.extern.log4j.Log4j2;

@Log4j2
@Service
@Transactional(timeout=30,
				readOnly = false,
				isolation = Isolation.READ_COMMITTED,
				rollbackFor = Throwable.class,
				propagation = Propagation.REQUIRED)
public class SysUserServiceImpl implements SysUserService{
	
	@Autowired
	private SysUserDao sysUserDao;
	@Autowired
	private SysUserRoleDao sysUserRoleDao;

	@Override
	@Transactional(readOnly = true)
	@RequiredLog("查询用户")
	public PageObject<SysUserDeptVo> findPageObjects(String username, Integer pageCurrent) {
		if(pageCurrent==null||pageCurrent<1)
			throw new IllegalArgumentException("当前页码值无效");
		int rowCount=sysUserDao.getRowCount(username);
		if(rowCount==0)
			throw new ServiceException("没有找到对应记录");
		int pageSize=3;
		int startIndex=(pageCurrent-1)*pageSize;
		List<SysUserDeptVo> records=sysUserDao.findPageObjects(username, startIndex, pageSize);
		
		return new PageObject<>(pageCurrent,pageSize,rowCount,records);
	}

	@Override
	@RequiredLog("禁用启用")
	@RequiresPermissions("sys:user:valid")
	public int validById(Integer id, Integer valid, String modifiedUser) {
		if(id==null||id<=0)
			throw new ServiceException("参数不合法,id="+id);
		if(valid!=1&&valid!=0)
			throw new ServiceException("参数不合法,valid="+valid);
		if(StringUtils.isEmpty(modifiedUser))
			throw new ServiceException("修改用户不能为空");
		int rows=sysUserDao.validById(id, valid, modifiedUser);
		if(rows==0)
			throw new ServiceException("修改用户不能为空");
		
		return rows;
	}

	@Override
	@RequiredLog("添加用户")
	public int saveObject(SysUser entity, Integer[] roleIds) {
		long start=System.currentTimeMillis();
		log.info("start:"+start);
		if(entity==null)
			throw new ServiceException("保存对象不能为空");
		if(StringUtils.isEmpty(entity.getUsername()))
			throw new ServiceException("用户名不能为空");
		if(StringUtils.isEmpty(entity.getPassword()))
			throw new ServiceException("密码不能为空");
		if(roleIds==null||roleIds.length==0)
			throw new ServiceException("至少为用户分配一个角色");
		String source=entity.getPassword();
		String salt=UUID.randomUUID().toString();
		SimpleHash sh=new SimpleHash("MD5", source, salt, 1);
		entity.setSalt(salt);
		entity.setPassword(sh.toHex());
		int rows=sysUserDao.insertObject(entity);
		sysUserRoleDao.insertObjects(entity.getId(), roleIds);
		long end = System.currentTimeMillis();
		log.info("end:"+end);
		log.info("total time :"+(end-start));
		return rows;
	}

	@Override
	public Map<String, Object> findObjetById(Integer userId) {
		if(userId==null||userId<=0)
			throw new ServiceException("参数数据不合法,userId="+userId);
		SysUserDeptVo user=sysUserDao.findObjectById(userId);
		if(user==null)
			throw new ServiceException("此用户已经不存在");
		List<Integer> roleIds=sysUserRoleDao.findRoleIdsByUserId(userId);
		Map<String,Object> map=new HashMap<>();
		map.put("user", user);
		map.put("roleIds", roleIds);
		return map;
	}

	@Override
	@RequiredLog("修改用户")
	public int updateObject(SysUser entity, Integer[] roleIds) {
		if(entity==null)
			throw new IllegalArgumentException("保存对象不能为空");
		if(StringUtils.isEmpty(entity.getUsername()))
			throw new IllegalArgumentException("用户名不能为空");
		if(roleIds==null||roleIds.length==0)
			throw new IllegalArgumentException("必须为其指定角色");
		int rows=sysUserDao.updateObject(entity);
		sysUserRoleDao.deleteObjectsByRoleId(entity.getId());
		sysUserRoleDao.insertObjects(entity.getId(), roleIds);
		return rows;
	}

	@Override
	@RequiredLog("修改密码")
	public int updatePassword(String password, String newPassword, String cfgPassword) {
		if(StringUtils.isEmpty(newPassword))
			throw new IllegalArgumentException("新密码不能为空");
		if(StringUtils.isEmpty(cfgPassword))
			throw new IllegalArgumentException("确认密码不能为空");
		if(!newPassword.equals(cfgPassword))
			throw new IllegalArgumentException("两次输入的密码不一致");
		if(StringUtils.isEmpty(password))
			throw new IllegalArgumentException("原密码不能为空");
		SysUser user=(SysUser) SecurityUtils.getSubject().getPrincipal();
		SimpleHash sh=new SimpleHash("MD5", password, user.getSalt(), 1);
		if(!user.getPassword().equals(sh.toHex()))
			throw new IllegalArgumentException("原密码不正确");
		String salt=UUID.randomUUID().toString();
		sh=new SimpleHash("MD5", newPassword, salt, 1);
		int rows=sysUserDao.updatePassword(sh.toHex(), salt, user.getId());
		if(rows==0)
			throw new ServiceException("修改密码失败");
		return rows;
	}

}
